package db

import (
	"fmt"
	"github.com/astaxie/beego"
	"labix.org/v2/mgo"
)

var (
	mgoSession   *mgo.Session
	databaseName = `auutasklist`
	dbip         = `localhost`
)

func getSession() *mgo.Session {
	if mgoSession == nil {
		//fmt.Println("null")
		if ar := beego.AppConfig.String("dbname"); ar != "" {
			databaseName = ar
		}
		if ar := beego.AppConfig.String("dbip"); ar != "" {
			dbip = ar
		}
		username := beego.AppConfig.String("dbuser")
		password := beego.AppConfig.String("dbpass")

		var err error
		dialinfo := mgo.DialInfo{
			Addrs:    []string{"localhost"}, // fails unless set to "localhost:27017"
			Database: databaseName,
			Username: username,
			Password: password,
		}
		mgoSession, err = mgo.DialWithInfo(&dialinfo)
		if err != nil {
			fmt.Println("Connect to the database at %s error.", dbip)
			panic(err) // no, not really
		}
		//mgoSession.SetMode(mgo., refresh)
		//defer mgoSession.Close()
	}

	return mgoSession.Clone()
}

func WithCollection(collection string, s func(*mgo.Collection) error) error {
	session := getSession()
	defer session.Close()
	c := session.DB(databaseName).C(collection)
	return s(c)
}
